package com.codename1.samples;


import com.codename1.io.AccessToken;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.io.Oauth2;
import com.codename1.ui.Button;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */
public class Oauth2Login {
private static  String REDIRECT_URI = "https://weblite.ca/a/auth4/loggedin.html";//https://cloud.codenameone.com/buildapp/loggedIn.html";
    private AccessToken accessToken;
    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });        
    }
    
    public void start() {
        //This needs to be at the begnning of the start method for Oauth2 to work 
        // correctly on the web.  This handles the login when the Oauth2 login page
        // redirects back tothe app
        if (Oauth2.handleRedirect(e->{


            if(e.getSource() instanceof AccessToken) {
                Log.p("Logged in: " + e);
                AccessToken token = (AccessToken)e.getSource();
                setAccessToken(token);
                showLoggedIn();
            } else {
                Log.p("Failed to login " + e.getSource());
                showLogin();

            }
            return;
            
        })) {
            // The Oauth redirect was handled.  Use the handleRedirect callback for control flow
            // do not continue with rest of start() method.
            return;
        }
        if(current != null){
            current.show();
            return;
        }
        showLogin();
    }
    
    private void doLogin() {
        
        Oauth2.setBackToParent(false);
        Oauth2 login = new Oauth2("https://auth.codenameone.com/auth/realms/Realm/protocol/openid-connect/auth?client_id=cn1cloudapp&scope=openid%20address&response_type=code&state=a2V5Y2xvYWs=", "cn1cloudapp", REDIRECT_URI, "openid address", 
                "https://auth.codenameone.com/auth/realms/Realm/protocol/openid-connect/token", null);
        // Important: On the web we need to use a redirect for Oauth instead of an iframe
        // NOTE: This needs to be accompanied by a call to Oauth2.handleRedirect() at the beginning of the start()
        // method.
        login.setUseRedirectForWeb(true);
        login.showAuthentication(e -> {
            Log.p("Logged in: " + e);
            if(e.getSource() instanceof AccessToken) {
                AccessToken token = (AccessToken)e.getSource();
                setAccessToken(token);
                showLoggedIn();
            }
        });
    }
    
    private void showLoggedIn() {
        Form f = new Form("Logged In", BoxLayout.y());
        f.add(new Label("You are logged in"));
        f.show();
    }
    
    private void showLogin() {
        Form f = new Form("Login", BoxLayout.y());
        Button b = new Button("Login");
        b.addActionListener(evt->{
            doLogin();
        });
        f.add(b);
        f.show();
    }

    private void setAccessToken(AccessToken tok) {
        accessToken = tok;
    }
    
    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }
    
    public void destroy() {
    }


}
